package com.shiyi.util;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.apache.http.entity.ContentType;
import org.apache.pdfbox.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author: muxiongxiong
 * @date: 2022年12月29日 15:35
 * 公众号：雄雄的小课堂
 * 博客：https://blog.csdn.net/qq_34137397
 * 个人站：http://www.穆雄雄.com
 * 个人站：http://www.muxiongxiong.cn
 * @Description: 类的描述
 */
public class FilesUtil {


    /**
     * 根据地址获得数据的输入流
     *
     * @param strUrl 网络连接地址
     * @return url的输入流
     */
    public static InputStream getInputStreamByUrl(String strUrl) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(20 * 1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), output);
            return new ByteArrayInputStream(output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 将网络地址转换成MultipartFile
     * @param strUrl
     * @return
     */
    public static MultipartFile onlineAddressTransferFile(String strUrl){
        MultipartFile file = null;
        try {
            String fileName = strUrl.substring(strUrl.lastIndexOf("/") + 1);
            InputStream  stream = getInputStreamByUrl(strUrl);
            if (!ObjectUtils.isEmpty(stream)) {
                 file = new MockMultipartFile(fileName, fileName, "", stream);
                return file;
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return file;
    }

}
